<template>
  <view class="login_outer">
    <beginOuterBox>
      <view slot="begintopImg">
        <image class="begin_title_img" src="@/static/begin/begintop.png" v-if="isShowLogo"></image>
      </view>
      <view slot="hellow">注册!</view>
      <view slot="titleText">SignUp～</view>
      <!-- 注册页 -->
      <view class="login_content_btnbox" slot="content">
        <u--form labelPosition="left" ref="uForm" :model="registerIptData" :rules="rules">
          <u-form-item ref="item1" prop="phone">
            <view class="login_content_phone">
              <view class="login_content_phone_img">
                <image src="@/static/login/phone.png"></image>
              </view>
              <u--input border="none" placeholder="请您输入手机号" v-model="registerIptData.phone" @blur="isShowLogo = true"
                @focus="isShowLogo = false">
              </u--input>
            </view>
          </u-form-item>
          <u-form-item ref="item2">
            <view class="login_content_verification">
              <view class="login_content_verification_ipu">
                <view class="login_content_verification_img">
                  <image src="@/static/login/verification.png"></image>
                </view>
                <u--input border="none" placeholder="请输入手机验证码" v-model="registerIptData.code" @blur="isShowLogo = true"
                  @focus="isShowLogo = false">
                </u--input>
              </view>
              <view class="login_content_verification_uToast">
                <u-toast ref="uToast"></u-toast>
                <u-code :seconds="seconds" startText="获取" changeText="x秒" @end="end" @start="start" ref="uCode"
                  @change="codeChange"></u-code>
                <view class="login_content_verification_uToast_btn" @click="getCanvasVerification">{{ tips }}</view>
              </view>
            </view>
          </u-form-item>
          <u-form-item ref="item3" prop="password">
            <view class="login_content_phone pawsword">
              <view class="login_content_phone_img">
                <image src="@/static/login/password.png"></image>
              </view>
              <u--input border="none" placeholder="请输入密码" v-model="registerIptData.password"
                :type="isShowPassword ? 'text' : 'password'" @blur="isShowLogo = true" @focus="isShowLogo = false">
                <view slot="suffix" @click="isShowPassword = !isShowPassword" style="margin-right: 20rpx;">
                  <u-icon name="eye-fill" v-if="isShowPassword"></u-icon>
                  <u-icon name="eye-off" v-else></u-icon>
                </view>
              </u--input>
            </view>
          </u-form-item>
          <u-form-item ref="item4" prop="confirmPassword">
            <view class="login_content_phone pawsword">
              <view class="login_content_phone_img">
                <image src="@/static/login/password.png"></image>
              </view>
              <u--input border="none" placeholder="请确认密码" v-model="registerIptData.confirmPassword"
                :type="isShowPassword2 ? 'text' : 'password'" @blur="isShowLogo = true" @focus="isShowLogo = false">
                <view slot="suffix" @click="isShowPassword2 = !isShowPassword2" style="margin-right: 20rpx;">
                  <u-icon name="eye-fill" v-if="isShowPassword2"></u-icon>
                  <u-icon name="eye-off" v-else></u-icon>
                </view>
              </u--input>
            </view>
          </u-form-item>
          <u-form-item ref="item5">
            <view class="login_content_verification_affirm">
              <view @click="getRegisterUser">
                <text>确定</text>
              </view>
            </view>
          </u-form-item>
        </u--form>
        <u-popup :show="isShowVerificationImgUrl" mode="center" round="30" :closeOnClickOverlay="true"
          @close="isShowVerificationImgUrl = false">
          <view class="verification_box">
            <view class="verificationImg" @click="getCanvasVerification">
              <image :src="verificationImgUrl.encode"></image>
            </view>
            <view class="verificationIpt">
              <view>
                <u--input border="none" placeholder="请输入图形验证码" v-model="sendVerificationCode">
                </u--input>
              </view>
            </view>
            <view class="verificationIpt_affirm">
              <view @click="reqSendNoteCode">
                <text>确定</text>
              </view>
            </view>
          </view>
        </u-popup>
      </view>
    </beginOuterBox>
  </view>
</template>

<script>
import beginOuterBox from "@/components/beginOuterBox.vue";
import { reqRegisterUser } from "@/api/register.js";
import { reqCanvasVerification, reqSendNoteCode } from "@/api/all.js";
import { mapMutations, mapActions,mapState } from "vuex";
export default {
  data() {
    return {
      // 短信验证码提示
      tips: "",
      // 短信验证码等待秒数
      seconds: 60,
      // 人机验证码
      verificationImgUrl: {},
      // 是否展示人机验证码
      isShowVerificationImgUrl: false,
      // 人机验证码
      sendVerificationCode: "",
      // 是否能发送验证码
      isSendVerificationCode: true,
      // 手机号格式是否正确
      // phoneFormat: false,
      // 注册参数
      registerIptData: {
        phone: "",
        code: "",
        password: "",
        confirmPassword: "",
      },
      isShowPassword: false,
      isShowPassword2: false,
      isShowLogo: true,

      rules: {
        // 字段名称
        phone: [
          {
            required: true,
            message: "请输入手机号",
            trigger: ["change", "blur"],
          },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // uni.$u.test.mobile()就是返回true或者false的
              this.phoneFormat = uni.$u.test.mobile(value);
              return uni.$u.test.mobile(value);
            },
            message: "手机号码不正确",
            // 触发器可以同时用blur和change
            trigger: ["change", "blur"],
          },
        ],
        // 字段名称
        password: [
          {
            required: true,
            message: "请输入密码",
            trigger: ["change", "blur"],
          },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9a-zA-Z]{6,20}$/;

              return reg.test(value);
            },
            message: "请输入字母、数字组合的密码",
            // 触发器可以同时用blur和change
            trigger: ["change", "blur"],
          },
        ],
        // 字段名称
        confirmPassword: [
          {
            required: true,
            message: "请输入确认密码",
            trigger: ["change", "blur"],
          },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9a-zA-Z]{6,20}$/;
              return reg.test(value);
            },
            message: "请输入字母、数字组合的密码",
            // 触发器可以同时用blur和change
            trigger: ["change", "blur"],
          },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              
              return this.registerIptData.password==this.registerIptData.confirmPassword;
            },
            message: "两次密码不一致",
            // 触发器可以同时用blur和change
            trigger: ["change", "blur"],
          },
        ],
      },
    };
  },
  methods: {
    ...mapMutations(["setAccountListData"]),
    ...mapActions(["setUserInfo"]),
    // 跳转选择登录或注册页面
    goBeginPage() {
      uni.navigateTo({
        url: "/pages/accountList/index",
      });
    },
    //获取人机校验码
    getCanvasVerification: _.throttle(async function () {
      if (!uni.$u.test.mobile(this.registerIptData.phone)) {
        uni.showToast({
          title: "手机号格式不正确",
          icon: "error",
        });
        return;
      }
      if (!this.isSendVerificationCode) {
        uni.showToast({
          title: "倒计时结束再发送",
          icon: "error",
        });
        return;
      }
      const result = await reqCanvasVerification();
      if (result.code == 200) {
        this.verificationImgUrl = result.data;
        this.isShowVerificationImgUrl = true;
      } else {
        uni.showToast({
          title: result.msg,
          icon: "error",
        });
      }
    }, 500),
    //发送短信
    async reqSendNoteCode() {
      if (!this.sendVerificationCode) {
        uni.showToast({
          title: "请输入图形验证码",
          icon: "error",
        });
      } else {
        const sendData = {
          phone: this.registerIptData.phone,
          captchaId: this.verificationImgUrl.id,
          captcha: this.sendVerificationCode,
          scenes: 1,
        };
        const result = await reqSendNoteCode(sendData);
        if (result.code == 200) {
          uni.showToast({
            title: "短信验证码发送成功",
            icon: "success",
          });
          this.getCode();
          this.isShowVerificationImgUrl = false;
        } else {
          uni.showToast({
            title: result.msg,
            icon: "error",
          });
          this.getCanvasVerification();
        }
      }
    },
    codeChange(text) {
      this.tips = text;
    },
    getCode() {
      if (this.$refs.uCode.canGetCode) {
        // 模拟向后端请求验证码
        uni.showLoading({
          title: "正在获取验证码",
        });
        setTimeout(() => {
          uni.hideLoading();
          // 这里此提示会被this.start()方法中的提示覆盖
          uni.$u.toast("验证码已发送");
          // 通知验证码组件内部开始倒计时
          this.$refs.uCode.start();
        }, 2000);
      } else {
        uni.$u.toast("倒计时结束后再发送");
      }
    },
    start() {
      this.isSendVerificationCode = false;
    },
    end() {
      this.isSendVerificationCode = true;
    },

    // 注册
    getRegisterUser: _.throttle(function () {
      let isSend = false;
      let hignArr = ["手机号", "短信验证码", "密码", "确认密码"];
      let hignIndex = 0;
      for (let key in this.registerIptData) {
        if (!this.registerIptData[key]) {
          isSend = false;
          break;
        } else {
          isSend = true;
        }
        hignIndex++;
      }

      if (
        this.registerIptData.password != this.registerIptData.confirmPassword
      ) {
        uni.showToast({
          title: "两次密码不一致",
          icon: "error",
        });
        isSend = false;
        return;
      }
      if (!uni.$u.test.mobile(this.registerIptData.phone)) {
        uni.showToast({
          title: "手机号格式不正确",
          icon: "error",
        });
        return;
      }
      const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9a-zA-Z]{6,20}$/;
      if (!reg.test(this.registerIptData.password)) {
        uni.showToast({
          title: "密码格式为6-20位数字加字母",
          icon: "error",
        });
        return;
      }
      if (isSend) {
        uni.showLoading({
          title: "注册中",
        });
        setTimeout(async () => {
          const result = await reqRegisterUser({
            ...this.registerIptData,
            wxCode: uni.getStorageSync("code"),
          });
          uni.hideLoading();
          if (result.code == 200) {
            this.setAccountListData(result.data);
            this.setUserInfo({
              phone: this.registerIptData.phone,
              agree: 1,
              password: this.registerIptData.password,
            });
            uni.setStorageSync("phone", this.registerIptData.phone),
              uni.showToast({
                title: "注册成功",
                icon: "success",
              });

          } else {
            this.getWxCode();
            uni.showToast({
              title: result.msg,
              icon: "error",
            });
          }
        }, 500);
      } else {
        uni.showToast({
          title: `${hignArr[hignIndex]}不能为空`,
          icon: "error",
        });
      }
    }, 1000),
    getUrlParam(name) {
      const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
      // const r = window.location.search.split('?')[1].match(reg);
      const r = window.location.search.split("?")[1];
      console.log(r);
      if (r) {
        const result = window.location.search
          .split("?")[1]
          .match(new RegExp("(^|&)" + "code" + "=([^&]*)(&|$)"));
        // return unescape(r[2]);
        uni.setStorageSync("code", result[2]);
        return result[2];
      }
      return null;
    },
    async getWxCode() {
      let appid = "wx9a11ba393646fe6d"; //公众号的APPID

      let code = this.getUrlParam("code"); //检查url中是否存在code

      let local = "https://xckx.zhilianmanbu.com/#/pages/register/index"; //测试路径，即当前h5页面的路径

      if (code == null || code === "") {
        //不存在就打开下面的地址进行授权

        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(
          local
        )}&response_type=code&scope=snsapi_userinfo&state=1&#wechat_redirect`;
        this.getUrlParam("code");
      } else {
        this.code = code;
      }
    },
  },
  onShow(){
    clearTimeout(this.KlineTimer)
    clearInterval(this.newKlineTimer)
  },
  computed:{
    ...mapState(['newKlineTimer','KlineTimer'])
  },
  components: {
    beginOuterBox,
  },
};
</script>

<style lang="scss" scoped>
.login_outer {
  width: 100vw;
  height: 100vh;

  .begin_title_img {
    width: 126rpx;
    height: 126rpx;
    position: absolute;
    top: 62rpx;
    left: 58rpx;
  }

  .login_content_btnbox {
    z-index: 999;
    position: absolute;
    top: 142rpx;
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;

    .login_content_phone {
      width: 545rpx;
      height: 75rpx;
      border: 3px solid #ff9e3c;
      border-radius: 26rpx;
      display: flex;
      align-items: center;

      .login_content_phone_img {
        width: 40rpx;
        height: 40rpx;
        margin-left: 14rpx;
        margin-right: 28rpx;

        image {
          width: 100%;
          height: 100%;
        }
      }
    }

    .login_content_verification {
      width: 556rpx;
      height: 75rpx;
      display: flex;
      align-items: center;
      // margin-top: -14rpx;

      .login_content_verification_ipu {
        width: 391rpx;
        height: 74rpx;
        border: 3px solid #ff9e3c;
        border-radius: 26rpx;
        display: flex;
        align-items: center;
      }

      .login_content_verification_img {
        width: 40rpx;
        height: 40rpx;
        margin-left: 14rpx;
        margin-right: 28rpx;

        image {
          width: 100%;
          height: 100%;
        }
      }

      .login_content_verification_uToast {
        width: 142rpx;
        height: 74rpx;
        background: #2f2a26;
        background: linear-gradient(to right, #666157 0%, #504c43 100%);
        border-radius: 26rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-left: 12rpx;

        .login_content_verification_uToast_btn {
          font-size: 31rpx;
          font-family: DreamHanSansSC;
          font-weight: normal;
          color: #fffaef;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
    }

    .login_content_phone.pawsword {
      margin-top: -10rpx;
    }

    .login_content_verification_affirm {
      position: fixed;
      display: flex;
      justify-content: center;
      margin-top: 120rpx;

      view {
        width: 545rpx;
        height: 108rpx;
        background: linear-gradient(to right, #ff7007 0%, #ffa749 100%);
        border-radius: 38rpx;
        display: flex;
        justify-content: center;
        align-items: center;

        text {
          font-size: 38rpx;
          font-family: DreamHanSansSC;
          font-weight: normal;
          color: #ffffff;
        }
      }
    }
  }

  .register_content_btnbox {
    z-index: 999;
    position: absolute;
    top: 192rpx;
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .verification_box {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 600rpx;
    height: 600rpx;

    .verificationIpt {
      width: 400rpx;
      height: 100rpx;
      border: 4rpx solid orange;
      border-radius: 38rpx;
      margin-top: 30rpx;
      display: flex;
      align-items: center;

      view {
        margin-left: 30rpx;
      }
    }

    .verificationImg {
      width: 400rpx;
      height: 200rpx;
      margin-top: 40rpx;

      image {
        width: 100%;
        height: 100%;
      }
    }

    .verificationIpt_affirm {
      display: flex;
      justify-content: center;
      margin-top: 30rpx;

      view {
        width: 400rpx;
        height: 108rpx;
        background: linear-gradient(to right, #ff7007 0%, #ffa749 100%);
        border-radius: 38rpx;
        display: flex;
        justify-content: center;
        align-items: center;

        text {
          font-size: 38rpx;
          font-family: DreamHanSansSC;
          font-weight: normal;
          color: #ffffff;
        }
      }
    }
  }
}
</style>
